<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      
      <el-form-item prop="homeId" label-width="120px">
        <el-input
          v-model="queryParams.homeId"
          placeholder="家庭ID"
          clearable
          size="small"
          style="width: 180px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item prop="address">
        <el-input
          v-model="queryParams.address"
          placeholder="家庭地址"
          clearable
          size="small"
          style="width: 180px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始更新时间"
          end-placeholder="结束更新时间"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="small"
          @click="handleAdd"
          v-hasPermi="['buz:home:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="small"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['buz:home:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          icon="el-icon-edit"
          size="small"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['buz:home:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          icon="el-icon-upload2"
          size="small"
          @click="handleImport"
          v-hasPermi="['system:user:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          icon="el-icon-download"
          size="small"
          @click="handleExport"
          v-hasPermi="['buz:home:export']"
        >导出</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="homeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="家庭ID" align="center" prop="homeId" />
      <el-table-column label="家庭名称" align="center" prop="homeName" />
      <el-table-column label="家庭地址" align="center" prop="address" :show-overflow-tooltip="true"/>
      <el-table-column label="业主信息" align="center" prop="userName" :show-overflow-tooltip="true"/>
      <el-table-column label="模型名称" align="center" prop="modelName" />
      <el-table-column label="房间描述" align="center" prop="description" :show-overflow-tooltip="true"/>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="160">
          <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
          </template>
      </el-table-column>
      <el-table-column label="操作" align="center"  width="160" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="addQrcodeFun(scope.$index,scope.row)"
            v-hasPermi="['buz:home:edit']"
          >生成二维码</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['buz:home:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改家庭房屋信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <h2>基础信息</h2>
        <el-row>
          <el-col :span="12">
            <el-form-item label="家庭名称" prop="homeName">
              <el-input v-model="form.homeName" style="width: 180px" placeholder="请输入家庭名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所在部门" prop="parentId">
              <el-select v-model="form.parentId" placeholder="请选择">
                  <el-option
                      v-for="dict in communityListArry"
                      :key="dict.id"
                      :label="dict.name"
                      :value="dict.id"
                  ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="房屋住址" prop="address">
              <el-input v-model="form.address" style="width: 180px" placeholder="请输入房屋地址"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="业主信息" prop="userId">
              <el-button type="text" v-model="form.userId"  @click="selectOwnerFun">{{ownerBindInput}}</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="模型绑定" prop="modelBind">
              <el-button type="text" v-model="form.modelId" @click="selectModelFun">{{modelBindInput}}</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <h2>房间信息</h2>
        <el-row>
            <el-input v-model="form.home" style="width: 180px;margin-left: 15px;" placeholder="选择房间"/>
            <el-input v-model="form.homeDes" style="width: 240px;margin-left: 50px;" placeholder="请输入房间名字"/>
        </el-row> -->
      </el-form>
       <!-- 绑定业主信息对话框 -->
      <el-dialog title="业主选择" :visible.sync="owneropen" width="750px" append-to-body>
        <el-form ref="formowner" :model="queryOwnerParams" :inline="true" label-width="68px">
          <el-form-item prop="userId">
              <el-input
                v-model="queryOwnerParams.userId"
                placeholder="用户ID"
                clearable
                size="small"
                style="width: 180px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item prop="userName">
              <el-input
                v-model="queryOwnerParams.userName"
                placeholder="用户账号"
                clearable
                size="small"
                style="width: 180px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            
            <el-form-item prop="userSex">
              <el-select
                v-model="queryOwnerParams.userSex"
                placeholder="用户性别"
                clearable
                size="small"
                style="width: 180px"
              >
                <el-option
                  v-for="dict in sexOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-date-picker
                v-model="dateRangeDialog"
                size="small"
                style="width: 240px"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="-"
                start-placeholder="开始更新时间"
                end-placeholder="结束更新时间"
              ></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="cyan" icon="el-icon-search" size="small" @click="handleOwnerQuery">搜索</el-button>
            </el-form-item>
        </el-form>
        <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionOwnerChange">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="用户ID" align="center" prop="userId" />
            <el-table-column label="登陆账号" align="center" prop="userName" :show-overflow-tooltip="true" />
            <!-- <el-table-column label="会员角色" align="center" prop="useRoles" /> -->
            <el-table-column label="会员昵称" align="center" prop="nickName" :show-overflow-tooltip="true" />
            <el-table-column label="手机号" align="center" prop="phonenumber" width="120" />
            <el-table-column label="会员性别" align="center" prop="useSex" />
            <el-table-column label="会员状态" align="center" prop="status" />
        </el-table>
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryOwnerParams.pageNum"
          :limit.sync="queryOwnerParams.pageSize"
          @pagination="getAppUserList"
        />
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitOwnerForm" :disabled="singleOwner">确 定</el-button>
          <el-button @click="cancelOwner">取 消</el-button>
        </div>
      </el-dialog>

       <!-- 绑定模型信息对话框 -->
      <el-dialog title="模型选择" :visible.sync="modelopen" width="750px" append-to-body>
        <el-form ref="formmodel" :model="queryModelParams" :inline="true" label-width="68px">
          <el-form-item prop="modelId">
              <el-input
                v-model="queryModelParams.modelId"
                placeholder="模型ID"
                clearable
                size="small"
                style="width: 180px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item prop="modelName">
              <el-input
                v-model="queryModelParams.modelName"
                placeholder="模型名称"
                clearable
                size="small"
                style="width: 180px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="cyan" icon="el-icon-search" size="small" @click="handleModelQuery">搜索</el-button>
            </el-form-item>
        </el-form>
        <el-table v-loading="loading" :data="modelList" @selection-change="handleSelectionModelChange">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="模型ID" align="center" prop="modelId" />
            <el-table-column label="模型名称" align="center" prop="modelName" :show-overflow-tooltip="true" />
            <el-table-column label="模型描述" align="center" prop="description" :show-overflow-tooltip="true" />
        </el-table>
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryModelParams.pageNum"
          :limit.sync="queryModelParams.pageSize"
          @pagination="getModelList"
        />
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitModelForm" :disabled="singleModel">确 定</el-button>
          <el-button @click="cancelModel">取 消</el-button>
        </div>
      </el-dialog>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 二维码弹窗 -->
    <el-dialog title="二维码" :visible.sync="qrcodeopen" width="400px" height="300px">
      <el-form ref="qrcodObj" :model="form" label-width="70px">
        <el-row>
          <el-col :span="10">
            <el-form-item label="家庭ID" prop="homeId">
              <span>{{qrcodObj.homeId}}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="家庭地址" prop="address">
              <div style="line-height: 17px;">
                <span >{{qrcodObj.address}}</span>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <div class="qrcode">
        <div ref="qrcode" id="qrcode"></div>
        <el-form>
          <el-form-item>
            <div style="text-align: center;color: #52d631;">
              <span>请将该二维码发给业主</span>
            </div>
          </el-form-item>
          <el-form-item style="text-align: center;">
            <el-button type="text" size='medium'  @click="downs">生成图片并保存</el-button>
          </el-form-item>
        </el-form>
      </div>

    </el-dialog>
  </div>
</template>

<script>
import { listHome, getHome, delHome, addHome, updateHome, listModel } from "@/api/buz/home";
import { listAppUser} from "@/api/system/user";
import { getCommunityList } from "@/api/buz/tenement";
import QRCode from 'qrcodejs2'
export default {
  name: "Home",
  data() {
    return {
      //二维码数据
      inviteCode:null,
       //二维码信息
      qrcodObj: {},
      qrCode:null,
      //二维码弹窗
      qrcodeopen: false,
       //社区列表数组
      communityListArry: [],
      ownerBindInput:'点击绑定业主信息',
      modelBindInput:'点击绑定模型信息',
      // 用户非单个禁用
      singleOwner: true,
      // 模型非单个禁用
      singleModel: true,
      // 用户非多个禁用
      multipleOwner: true,
      // 模型非多个禁用
      multipleModel: true,
      // 是否显示模型绑定弹出层
      modelopen: false,
      //模型列表数据
      modelList: [],
      // 是否显示业主绑定弹出层
      owneropen: false,
      //用户列表数据
      userList: [],
      // 日期范围
      dateRange: [],
      //弹窗时间范围
      dateRangeDialog: [],
      // 角色数据字典
      userRolesOptions: [],
      // 状态数据字典
      statusOptions:[],
      // 性别状态字典
      sexOptions: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 家庭房屋信息表格数据
      homeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        address: null,
        deptId: null,
      },
      queryOwnerParams: {
        pageNum: 1,
        pageSize: 10,
        userName: null,
        userId: null,
      },
      queryModelParams: {
        pageNum: 1,
        pageSize: 10,
        modelName: null,
        modelId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        homeName: [
          { required: true, message: "家庭名称不能为空", trigger: "blur" }
        ],
        address: [
          { required: true, message: "房屋住址不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_user_sex").then(response => {
      this.sexOptions = response.data;
    });
  },
  methods: {
    /** 查询家庭房屋信息列表 */
    getList() {
      this.loading = true;
      listHome(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.homeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.ownerBindInput = '点击绑定业主信息'
      this.modelBindInput = '点击绑定模型信息'
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        homeId: null,
        address: null,
        deptId: null,
        inviteCode: null,
        modelId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange=[];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.homeId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加家庭房屋信息";
      this.ownerBindInput='点击绑定业主信息',
      this.modelBindInput='点击绑定模型信息',
      this.getCommunityList();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const homeId = row.homeId || this.ids
      getHome(homeId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改家庭房屋信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.homeId != null) {
            updateHome(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addHome(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const homeIds = row.homeId || this.ids;
      this.$confirm('是否确认删除家庭房屋信息编号为"' + homeIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delHome(homeIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('buz/home/export', {
        ...this.queryParams
      }, `buz_home.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "家庭导入";
      // this.upload.open = true;
    },
    // 多选框选中数据
    handleSelectionOwnerChange(selection) {
      this.singleOwner = selection.length!==1
      this.form.userId = selection.map(item => item.userId)[0]
      this.multipleOwner = !selection.length
    },
    // 多选框选中数据
    handleSelectionModelChange(selection) {
      this.singleModel = selection.length!==1
      this.form.modelId = selection.map(item => item.modelId)[0]
      this.multipleModel = !selection.length
    },
    //业主绑定弹窗
    selectOwnerFun(){
      this.owneropen = true;
      this.getAppUserList();

    },
    //模型绑定弹窗
    selectModelFun(){
      this.modelopen = true;
      this.getModelList();
    },
    /** 查询用户列表 */
    getAppUserList() {
      this.loading = true;
      listAppUser(this.addDateRange(this.queryOwnerParams, this.dateRange)).then(response => {
            this.userList = response.rows;
            this.total = response.total;
            this.loading = false;
        }
      );
    },
    /** 查询模型列表 */
    getModelList() {
      this.loading = true;
      listModel(this.queryModelParams).then(response => {
            this.modelList = response.rows;
            this.total = response.total;
            this.loading = false;
        }
      );
    },
    /** 业主搜索按钮操作 */
    handleOwnerQuery() {
      this.queryParams.pageNum = 1;
      this.getAppUserList();
    },
    /** 模型搜索按钮操作 */
    handleModelQuery() {
      this.queryModelParams.pageNum = 1;
      this.getModelList();
    },
    // 取消按钮
    cancelOwner() {
      this.owneropen = false;
      this.ownerBindInput = '点击绑定业主信息'
      // this.reset();
    },
    // 取消按钮
    cancelModel() {
      this.modelopen = false;
      this.modelBindInput = '点击绑定模型信息'
      // this.reset();
    },
    //业主绑定弹窗确定
    submitOwnerForm(){
      this.owneropen = false;
      this.ownerBindInput = this.form.userId;
    },
    //模型绑定弹窗确定
    submitModelForm(){
      this.modelopen = false;
      this.modelBindInput = this.form.modelId;
      
    },
    //获取社区数据
    getCommunityList(){
      getCommunityList().then(response => {
        if (response.code === 200) {
          this.communityListArry = response.data;
        }
      });
    },
    // 生成二维码弹窗
    addQrcodeFun(index, row){
      this.qrcodeopen=true;
      this.qrcodObj.homeId=row.homeId;
      this.qrcodObj.address=row.address;
      this.inviteCode = row.inviteCode;
       this.qrcode = this.creatQrCode()
      
    },
    //生成二维码数据
    creatQrCode() {
        this.$nextTick(() => {
          this.$refs.qrcode.innerHTML = "";
          let qr = new QRCode(this.$refs.qrcode, {
            text: this.inviteCode ? '邀请码: ' + this.inviteCode : '邀请码已使用', 
            width: 200,
            height: 200,
            colorDark: '#000000',
            colorLight: '#ffffff',
            correctLevel: QRCode.CorrectLevel.H
          })
        })
    },
    //保存二维码图片
    downs(){
      // 找到canvas标签
      let myCanvas = document.getElementById('qrcode').getElementsByTagName('canvas');
      let img=document.getElementById('qrcode').getElementsByTagName('img')
      // 创建一个a标签节点
      let a= document.createElement("a")
      //设置a标签的href属性（将canvas变成png图片）
      let imgURL=myCanvas[0].toDataURL('image/jpg');
      let ua = navigator.userAgent;
      if (ua.indexOf("Trident") != -1 && ua.indexOf("Windows") != -1) { // IE内核 并且  windows系统 情况下 才执行;
          var bstr = atob(imgURL.split(',')[1])
          var n = bstr.length
          var u8arr = new Uint8Array(n)
          while (n--) {
            u8arr[n] = bstr.charCodeAt(n)
          }
          var blob = new Blob([u8arr])
          window.navigator.msSaveOrOpenBlob(blob, this.qrcodObj.homeId + '.' + 'png')
      }else if(ua.indexOf("Firefox") > -1){ //火狐兼容下载
          let blob = this.base64ToBlob(imgURL); //new Blob([content]);
          let evt = document.createEvent("HTMLEvents");
          evt.initEvent("click", true, true);//initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
          a.download = ' ';//下载图片名称，如果填内容识别不到，下载为未知文件，所以我这里就不填为空
          a.href = URL.createObjectURL(blob);
          a.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true, view: window}));//兼容火狐
      }else{ //谷歌兼容下载
          img.src=myCanvas[0].toDataURL('image/jpg');
          // a.href = myCanvas[0].toDataURL('image/png').replace('image/png', 'image/octet-stream')
          a.href=img.src
          //设置下载文件的名字
          a.download = this.qrcodObj.homeId;
            //点击
          a.click()
      }
    },
    //base64转blob
    base64ToBlob(code) {
        let parts = code.split(';base64,');
        let contentType = parts[0].split(':')[1];
        let raw = window.atob(parts[1]);
        let rawLength = raw.length;
        let uInt8Array = new Uint8Array(rawLength);
        for (let i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
        }
        return new Blob([uInt8Array], {type: contentType});
    }
  }
};
</script>
<style lang="scss">
.home {
  padding: 20px;
  background: #000;
}
.qrcode {
  display: inline-block;
  margin-left: 75px;
  img {
    padding: 6px;
    background-color: #fff;
  }
}
</style>